package chapter02.part06;

import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 文件加锁
 * 需要注意的是, 具体效果和操作系统有关
 * 
 * @author insight
 * @since 2021/8/25
 */
public class FileLockTest2 {
    public static void main(String[] args) throws IOException {
        Path path = Paths.get("chapter02-io/src/main/resources/test.txt");
        
        // 调用 FileChannel 来操控文件锁
        FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE,
                StandardOpenOption.READ);
        // 读写锁测试
        try (FileLock lock = channel.tryLock(3, 10, false)) {
            if (lock == null) {
                System.out.println("Try Lock Failed!");
            } else {
                System.out.println("Try Lock Successed!");
            } 
        }

        // 共享锁测试
        /*try (FileLock lock = channel.tryLock(0, 10, true)) {
            if (lock == null) {
                System.out.println("Try Lock Failed!");
            } else {
                System.out.println("Try Lock Successed!");
            }
        }*/
    }
}